package com.zhonghui.common.core.interceptor;

import com.zhonghui.common.core.utils.JwtUtils;
import com.zhonghui.common.core.utils.RedisUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zhonghui.common.core.constant.FwConstants.ADMIN_LOGIN_TOKEN;
import static com.zhonghui.common.core.constant.FwConstants.USER_LOGIN_TOKEN;

/**
 * jwt令牌校验的拦截器
 * @author: FL
 * @create: 2024 2024/5/3 13:40
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private JwtUtils jwtUtils;
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("Authorization");
        log.info("请求头中的令牌：{}",token);
        //判断令牌是否存在，如果不存在，则拦截
        if (StringUtils.isBlank(token)){
            log.info("请求头中的令牌为空，请登录");
            response.setStatus(401);
            return false;
        }
        log.info("请求头中的令牌：{}",token);
        //解析令牌
        if (redisUtils.hasKey(USER_LOGIN_TOKEN+token)
                && !(jwtUtils.isExpired(token))
                && jwtUtils.verify(token)){

            return true;
        }else if (redisUtils.hasKey(ADMIN_LOGIN_TOKEN+token)
                && !(jwtUtils.isExpired(token))
                && jwtUtils.verify(token)){
            return true;
        }
        else {
            log.info("令牌已过期，请重新登录");
            response.setStatus(401);
            return false;
        }
    }
}
